package com.hice.demo.sbdbra.common.spring;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class DateConverter implements Converter<String, Date> {
    private static Logger log = LoggerFactory.getLogger(DateConverter.class);

    public Date convert(String source) {
        if (StringUtils.isNotBlank(source)) {
            String format = "yyyy-MM-dd HH:mm:ss";
            if (source.length() == 10)
                format = "yyyy-MM-dd";
            else {
                format = format.substring(0, source.length());
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat(format);
            dateFormat.setLenient(false);
            try {
                return dateFormat.parse(source);
            } catch (Exception e) {
                log.error("date convert error.", e);
            }
        }
        return null;
    }
}